<script setup lang="ts">
import {
  deleteBaremetalNodeApi,
  getBaremetalNodeListApi,
  updateBaremetalNodeTagsApi,
} from '@/apis/modules/node'
import { Message } from '@arco-design/web-vue'
import SetTagDialog from '../components/SetTagDialog.vue'
import EditNode from './components/EditNode.vue'
import NodeStatus from './components/NodeStatus.vue'
import useConfig from './useConfig'

const { columns } = useConfig()
const queryParams = ref({
  region_id: '',
  tag: '',
  status: '',
  alloc: '',
})
const {
  data: tableData,
  pagination,
  loading,
  run,
} = useListRequest(getBaremetalNodeListApi, {
  immediate: true,
  params: queryParams,
})
const { tableRef, selectedKeys, selectionRows, decPageByData } = useTable(
  run,
  tableData,
)
const {
  open: openSetTagDialog,
  visible: setTagDialogVisible,
  data: setTagDialogData,
} = usePopup()

async function handleUpdateTag(
  data: Array<{ id: string, region_id: string }>,
  tag: string,
) {
  await updateBaremetalNodeTagsApi({
    ids: data.map(item => item.id),
    tag,
  })
  await run(queryParams)
  Message.success('设置成功')
}
function batchSetTag() {
  const data
    = selectionRows.value.map(item => ({
      id: item.id,
      region_id: item.region_id,
    })) ?? []
  openSetTagDialog({ data })
}
const {
  open: openEditNode,
  visible: editNodeVisible,
  data: nodeData,
} = usePopup()

// 删除节点
const handleDelete = useConfirm<string>(
  {
    title: '删除节点',
    content: '节点删除后不可恢复，确定要删除该节点吗？',
    width: 480,
    closable: false,
    okText: '删除',
  },
  async (id) => {
    await deleteBaremetalNodeApi({ id })
    decPageByData(pagination.value, tableData, selectedKeys)
    await run()
  },
)

const { allRegionOptions } = useRegions()
</script>

<template>
  <main-container
    :loading="loading"
    :pagination="pagination"
    @run="run"
  >
    <template #header>
      <a-button
        type="primary"
        @click="openEditNode()"
      >
        新建节点
      </a-button>
      <a-select
        v-model="queryParams.region_id"
        placeholder="请选择区域"
        :options="[{ label: '全部区域', value: '' }, ...allRegionOptions]"
        class="!w-34"
        @change="run"
      />
      <a-select
        v-model="queryParams.status"
        placeholder="请选择节点状态"
        :options="nodeStatusOptions"
        class="!w-34"
        @change="run"
      />
      <a-select
        v-model="queryParams.alloc"
        placeholder="请选择分配状态"
        :options="nodeAllocStatusOptions"
        class="!w-34"
        @change="run"
      />
      <a-input-search
        v-model="queryParams.tag"
        placeholder="请输入标签搜索"
        class="!w-58"
        @change="run"
      />
    </template>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      v-model:selected-keys="selectedKeys"
      :columns="columns"
      :data="tableData"
      :row-selection="defaultRowSelection"
    >
      <template #status="{ record }">
        <node-status
          :id="record?.id"
          :status="record.status"
          @refresh="run"
        />
      </template>
      <template #tag="{ record }">
        <div class="w-fit flex items-center">
          <text-ell>{{ record.tag || '-' }}</text-ell>
          <i-icons-edit
            class="hover-visible__tr ml-1 size-4 cursor-pointer text-primary-6"
            @click="
              openSetTagDialog({
                data: [{ id: record.id, region_id: record.region_id }],
                tag: record.tag,
              })
            "
          />
        </div>
      </template>
      <template #actions="{ record }">
        <a-link @click="openEditNode(record)">
          <i-icons-edit />
        </a-link>
        <a-link
          status="danger"
          @click="handleDelete(record.id)"
        >
          <i-icons-delete />
        </a-link>
      </template>
    </a-table>
    <template
      v-if="selectedKeys.length > 0"
      #total
    >
      <div class="flex-shrink-0">
        <a-button
          type="outline"
          class="mr-2"
          @click="batchSetTag"
        >
          设置标签
        </a-button>
        <span class="text-color-3">{{ `已选${selectedKeys.length}条` }}</span>
      </div>
    </template>
    <set-tag-dialog
      v-model:visible="setTagDialogVisible"
      :record="setTagDialogData"
      :submit="handleUpdateTag"
    />
    <edit-node
      v-model:visible="editNodeVisible"
      :record="nodeData"
      @success="run"
    />
  </main-container>
</template>

<style scoped></style>
